package com.shenhaofeng.app.utils;

import android.app.Activity;
import android.view.KeyEvent;
import android.widget.Toast;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 双击退出应用
 * Created by Administrator on 2016/5/12.
 */
public class DoubleHitQuitHelper {

    //2000毫秒内双击将会退出程序
    private static final int TIME = 2000;

    private Timer timer;
    private boolean canFinish = false;
    private Toast toast;


    public boolean onKeyUp(Activity activity, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (canFinish) {
                if (toast != null) {
                    toast.cancel();
                }
                activity.finish();
                return true;
            }
            if (timer != null) {
                timer.cancel();
            }
            timer = new Timer();
            timer.schedule(new Task(), TIME);
            if (toast != null) {
                toast.cancel();
            }
            toast = Toast.makeText(activity, "再次轻触退出程序", Toast.LENGTH_SHORT);
            toast.show();
            canFinish = true;
            return true;
        } else {
            return false;
        }
    }


    private class Task extends TimerTask {

        @Override
        public void run() {
            canFinish = false;
        }
    }


}
